import React, { useEffect, useState } from 'react';
import { Box, ListItem, ListItemAvatar, ListItemText, Avatar, Typography, Badge, IconButton, TextField } from '@mui/material';
import { Search as SearchIcon } from '@mui/icons-material';
import { VariableSizeList } from 'react-window';



const ContactList = React.memo(({ onSelectContact, selectedContactId, contacts = {} }) => {
  const listRef = React.useRef();
  const [searchText, setSearchText] = useState('');
  
  // 监听联系人列表变化
  useEffect(() => {
    console.log('联系人列表变化:', contacts);
    if (listRef.current) {
      listRef.current.resetAfterIndex(0);
    }
  }, [contacts]);

  // 格式化时间显示
  const formatTime = (timestamp) => {
    const date = new Date(timestamp);
    const now = new Date();
    
    // 重置时间部分，只比较日期部分
    const dateWithoutTime = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const nowWithoutTime = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    
    // 计算日期差异（毫秒转天数）
    const diffTime = nowWithoutTime - dateWithoutTime;
    const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24));
    
    // 获取时间部分（小时:分钟）
    const timeStr = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    if (diffDays === 0) {
      // 当天消息只显示时间
      return timeStr;
    } else if (diffDays === 1) {
      // 昨天的消息显示"昨天+时间"
      return `昨天 ${timeStr}`;
    } else if (diffDays < 7) {
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return days[date.getDay()];
    } else {
      // 更早的消息显示日期
      return date.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
    }
  };

  const itemSize = 72;

const Row = ({ index, style, data }) => {
  const contact = data[index];
  
  return (
    <div style={style}>
      <ListItem 
        alignItems="flex-start"
        sx={{
          padding: '11px 12px',
          minHeight: '48px',
          cursor: 'pointer',
          backgroundColor: contact.id === selectedContactId ? '#d4d4d4' : 'transparent',
          '&:hover': {
            backgroundColor: contact.id === selectedContactId ? '#d4d4d4' : '#e6e6e6'
          }
        }}
        onClick={() => onSelectContact(contact.id)}
      >
        <ListItemAvatar>
          <Badge
            color="error"
            badgeContent={contact.unread}
            invisible={contact.unread === 0}
            sx={{ 
              '& .MuiBadge-badge': { 
                right: 3, 
                top: 3,
                padding: '0 4px',
                height: 16,
                minWidth: 16
              } 
            }}
          >
            <Avatar src={contact.avatar} alt={contact.name} />
          </Badge>
        </ListItemAvatar>
        <ListItemText
          primary={
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography component="span" variant="body1" sx={{ 
                fontWeight: contact.unread > 0 ? 'bold' : 'normal', 
                fontSize: '0.875rem',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                maxWidth: '160px'
              }}>
                {contact.name}
              </Typography>
              <Typography component="span" variant="caption" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                {formatTime(contact.timestamp)}
              </Typography>
            </Box>
          }
          secondary={
            <Typography
              component="span"
              variant="body2"
              color="text.primary"
              sx={{
                color: contact.unread > 0 ? 'text.primary' : 'text.secondary',
                fontWeight: contact.unread > 0 ? 'medium' : 'normal',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                display: '-webkit-box',
                WebkitLineClamp: 1,
                WebkitBoxOrient: 'vertical',
                fontSize: '0.8125rem'
              }}
            >
              {contact.lastMessage}
            </Typography>
          }
        />
      </ListItem>
    </div>
  );
};

const getItemSize = () => itemSize;

// 过滤联系人列表
  const filteredContacts = Object.values(contacts).filter(contact => {
    if (!searchText) return true;
    const searchLower = searchText.toLowerCase();
    return (
      contact.name.toLowerCase().includes(searchLower) ||
      (contact.lastMessage && contact.lastMessage.toLowerCase().includes(searchLower))
    );
  });

  // 排序联系人列表（按时间降序）
  const contactItems = filteredContacts.sort((a, b) => {
    return new Date(b.timestamp) - new Date(a.timestamp);
  });

return (
  <Box sx={{ height: '100%', width: '100%', bgcolor: '#f5f5f5' }}>
    {/* 搜索框 */}
    <Box sx={{ 
      p: 1.2, 
      bgcolor: '#f5f5f5', 
      color: 'text.primary',
      display: 'flex', 
      alignItems: 'center',
      gap: 1
    }}>
        <TextField
          size="small"
          placeholder="搜索联系人"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          sx={{ 
            flexGrow: 1,
            '& .MuiOutlinedInput-root': {
              borderRadius: 20,
              backgroundColor: '#fff',
              height: 30,
              padding: '6px 12px'
            }
          }}
        />
        <IconButton color="primary" size="small" sx={{ '& svg': { color: '#595959' } }}>
          <SearchIcon />
        </IconButton>
      </Box>
      
      <Box sx={{ flex: 1 }}>
      <VariableSizeList
        height={window.innerHeight - 56}
        width="100%"
        itemCount={contactItems.length}
        itemSize={getItemSize}
        itemData={contactItems}
        ref={listRef}
      >
        {Row}
      </VariableSizeList>
    </Box>
    </Box>
  );
});
export default ContactList;